package cn.tianyigps.m7.template;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Optional;

/**
 * Created with IDEA
 *
 * @description: 接口调用
 * @author: cui.guibin
 * @create: 2019/4/16 19:24
 **/
public class RestTemplate {


    public static boolean post(String url, Object reply) throws IOException {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置请求的header
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");

        // 设置请求的参数
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(reply);
        StringEntity entity = new StringEntity(json, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        String json2 = EntityUtils.toString(response.getEntity(), "utf-8");
        JsonNode jsonNode = mapper.readTree(json2);
        if (!Optional.ofNullable(jsonNode).isPresent())
            return false;
        JsonNode jsonNode1 = jsonNode.get("code");
        if (!Optional.ofNullable(jsonNode1).isPresent())
            return false;
        if ("200".equals(jsonNode1.asText()))
            return true;
        else
            return false;
    }
}
